package com.cy.controller;

import com.cy.annotation.SysLog;
import com.cy.entity.Member;
import com.cy.enumresource.IsInitEnum;
import com.cy.enumresource.StateEnum;
import com.cy.service.MemberService;
import com.cy.util.ExportExcel;
import com.cy.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 
 * 
 * @author chenyi
 * @email 228112142@qq.com
 * @date 2017-08-08 17:35:59
 */
@Controller
@RequestMapping("/init/user/")
public class InitUserController {
	@Autowired
	private MemberService memberService;
	
	/**
	 * 列表
	 */
    @ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("member:list")
	public R list(@RequestParam Map<String, Object> params){
    	//是否是首批用户
		params.put("isInit", IsInitEnum.YES.getCode());
		//查询列表数据
        Query query = new Query(params);

		List<Member> memberList = memberService.queryList(query);
		int total = memberService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(memberList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}

	/**
	 * 导出
	 */
	@ResponseBody
	@SysLog("导入首批会员")
	@RequestMapping("/importMember")
	@RequiresPermissions("member:list")
	public R importMember(@RequestParam("file") MultipartFile file){
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		InputStream is= null;
		try {
			is = file.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		ExportExcel.getAllByExcel(is);
		return R.ok();
	}

    /**
     * 跳转到新增页面
     **/
    @RequestMapping("/add")
    @RequiresPermissions("member:save")
    public String add(){
        return "inituser/add.jsp";
    }

    /**
     *   跳转到修改页面
     **/
    @RequestMapping("/edit/{id}")
    @RequiresPermissions("member:update")
    public String edit(HttpServletRequest request, Model model, @PathVariable("id") Long id){
			Member member = memberService.queryObject(id);
        model.addAttribute("model", member);
        return "inituser/edit.jsp";
    }

	/**
	 * 信息
	 */
    @ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("member:info")
	public R info(@PathVariable("id") Long id){
		Member member = memberService.queryObject(id);
		
		return R.ok().put("member", member);
	}
	
	/**
	 * 保存
	 */
    @ResponseBody
	@SysLog("保存首批用户")
	@RequestMapping("/save")
	@RequiresPermissions("member:save")
	public R save(@RequestBody Member member){
    	//验证参数
		verifyForm(member);
    	//随机生成推荐码
    	String recommendCode= UUID.getCode();
		List<Member> memberList = memberService.findByCode(recommendCode);
		//如果推荐码已存在，重新生成
		while (memberList!=null&&memberList.size()>0){
			recommendCode= UUID.getCode();
			memberList = memberService.findByCode(recommendCode);
			if(memberList==null||memberList.size()==0){
				break;
			}
		}
		member.setPayTime(new Date());
		member.setRecommendCode(recommendCode);
		member.setIsInit(IsInitEnum.YES.getCode());
		member.setTeamParentAccount("-");
		member.setRecommendAccount("-");
		member.setPayAmount("-");
		member.setRecommendLowerNumber(0);
		memberService.saveMemberAndTeam(member);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
    @ResponseBody
	@SysLog("修改首批用户")
	@RequestMapping("/update")
	@RequiresPermissions("member:update")
	public R update(@RequestBody Member member){
		memberService.update(member);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
    @ResponseBody
	@SysLog("删除首批用户")
	@RequestMapping("/delete")
	@RequiresPermissions("member:delete")
	public R delete(@RequestBody Long[] ids){
		memberService.deleteBatch(ids);
		
		return R.ok();
	}

	/**
	 * 启用
	 */
	@ResponseBody
	@SysLog("启用首批用户")
	@RequestMapping("/enable")
	@RequiresPermissions("member:update")
	public R enable(@RequestBody Long[] ids){
		String stateValue=StateEnum.ENABLE.getCode();
		memberService.updateState(ids,stateValue);
		return R.ok();
	}
	/**
	 * 禁用
	 */
	@SysLog("禁用首批用户")
	@ResponseBody
	@RequestMapping("/limit")
	@RequiresPermissions("member:update")
	public R limit(@RequestBody Long[] ids){
		String stateValue=StateEnum.LIMIT.getCode();
		memberService.updateState(ids,stateValue);
		return R.ok();
	}
	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(Member member) {
		//验证团队码是否已存在
		List<Member> memberList = memberService.findByTeamCode(member.getTeamCode());
		if(memberList!=null&&memberList.size()>0){
			throw new RRException("该团队码已存在!");
		}
		//验证云支付账号是否已存在
		 memberList = memberService.findByAccount(member.getAccount());
		if(memberList!=null&&memberList.size()>0){
			throw new RRException("该云支付账号已存在!");
		}
		if (StringUtils.isBlank(member.getAccount())) {
			throw new RRException("云支付账号不能为空");
		}


	}
}
